﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace carApp.Libs
{
    public class Security
    {
        public static string DesKey = "houfangs";
        #region AES
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="key">加密的密码</param>
        /// <returns></returns>
        public static string EncryptAES(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DecryptAES(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Convert.FromBase64String(str);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }
        #endregion

        #region md5
        /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string EncryptMD5(string str)
        {
            byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');

            return ret;
        }

        /// <summary>
        /// 复合MD5
        /// </summary>
        /// <param name="key">因子</param>
        /// <param name="str">明文</param>
        /// <returns></returns>
        public static string ComplexMD5(string key, string str)
        {
            return EncryptMD5(StructureMD5(key, str));
        }
        /// <summary>
        /// 构造复合串
        /// </summary>
        /// <param name="key">因子</param>
        /// <param name="str">明文</param>
        /// <returns></returns>
        private static string StructureMD5(string key, string str)
        {
            if (key == "")
                key = DesKey;
            return str + key;
        }
        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>
        public static string GetMD5(string str, string inputCharset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(inputCharset).GetBytes(str));
            System.Text.StringBuilder sb = new System.Text.StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
        #endregion

        #region sha
        public static string GetSwcSHA1(string value)
        {
            SHA1 algorithm = SHA1.Create();//MD5 algorithm = MD5.Create();
            byte[] data = algorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value));
            string sh1 = "";
            for (int i = 0; i < data.Length; i++)
            {
                sh1 += data[i].ToString("x2").ToUpperInvariant();
            }
            return sh1;
        }
        /// <summary>
        /// SHA256函数
        /// </summary>
        /// /// <param name="str">原始字符串</param>
        /// <returns>SHA256结果</returns>
        public static string SHA256(string str)
        {
            byte[] SHA256Data = System.Text.Encoding.UTF8.GetBytes(str);
            SHA256Managed Sha256 = new SHA256Managed();
            byte[] Result = Sha256.ComputeHash(SHA256Data);
            return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
        }
        #endregion

        #region DES
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string EncryptDES(string Text, string sKey)
        {
            if (sKey == "")
                sKey = DesKey;
            try
            {
                byte[] rgbKey = System.Text.Encoding.UTF8.GetBytes(sKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(Text);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                System.IO.MemoryStream mStream = new System.IO.MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return "";
            }
        }
        private static byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string DecryptDES(string Text, string sKey)
        {
            if (sKey == "")
                sKey = DesKey;
            try
            {
                byte[] rgbKey = System.Text.Encoding.UTF8.GetBytes(sKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(Text);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                System.IO.MemoryStream mStream = new System.IO.MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return System.Text.Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region RAS
        //加密
        public static string EncrypRAS(string express)
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = DesKey;//密匙容器的名称，保持加密解密一致才能解密成功
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] plaindata = System.Text.Encoding.Default.GetBytes(express);//将要加密的字符串转换为字节数组
                byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组
                return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
            }
        }
        //解密
        public static string DecryptRAS(string ciphertext)
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = DesKey;
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] encryptdata = Convert.FromBase64String(ciphertext);
                byte[] decryptdata = rsa.Decrypt(encryptdata, false);
                return System.Text.Encoding.Default.GetString(decryptdata);
            }
        }
        #endregion

        #region 将加密串变为数字
        private static int HexChar2Value(string hexChar)
        {
            switch (hexChar)
            {
                case "0":
                case "1":
                case "2":
                case "3":
                case "4":
                case "5":
                case "6":
                case "7":
                case "8":
                case "9":
                    return Convert.ToInt32(hexChar);

                case "a":
                case "A":
                    return 10;

                case "b":
                case "B":
                    return 11;

                case "c":
                case "C":
                    return 12;

                case "d":
                case "D":
                    return 13;

                case "e":
                case "E":
                    return 14;

                case "f":
                case "F":
                    return 15;
            }
            return 0;
        }
        private static string Hex2Ten(string hex)
        {
            int num = 0;
            int startIndex = 0;
            int num3 = hex.Length - 1;
            while (startIndex < hex.Length)
            {
                num += HexChar2Value(hex.Substring(startIndex, 1)) * ((int)Math.Pow(16.0, (double)num3));
                num3--;
                startIndex++;
            }
            return num.ToString();
        }
        /// <summary>
        /// 转换为数字
        /// </summary>
        /// <param name="AsMachineID">MD5明文</param>
        /// <param name="sFactStr">因子</param>
        /// <returns></returns>
        public static string MD5toDec(string AsMachineID, string sFactStr)
        {
            string str2 = "";
            if (sFactStr == "")
            {
                sFactStr = DesKey;
            }
            if (AsMachineID == "")
            {
                return "";
            }
            string str3 = EncryptMD5(AsMachineID + sFactStr);
            for (int i = 1; i < 0x20; i++)
            {
                int num2;
                if (i == 1)
                {
                    num2 = (int.Parse(Hex2Ten(str3.Substring(0, 2))) + 1) % 8;
                    if (((i % 8) == 0) && (i != 0x20))
                    {
                        str2 = str2 + num2.ToString();
                    }
                    else
                    {
                        str2 = str2 + num2.ToString();
                    }
                }
                else if ((i % 2) == 0)
                {
                    num2 = (int.Parse(Hex2Ten(str3.Substring(i, 2))) + 1) % 8;
                    if (((i % 8) == 0) && (i != 0x20))
                    {
                        str2 = str2 + num2.ToString();
                    }
                    else
                    {
                        str2 = str2 + num2.ToString();
                    }
                }
            }
            return str2;
        }

        #endregion

        public static string CreateMd5Sign(Dictionary<string, string> parameters)
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(parameters.Keys);
            akeys.Sort();//sort
            foreach (string k in akeys)
            {
                if (k != "sign")
                {
                    string v = (string)parameters[k];
                    sb.Append(k + "=" + v + "&");
                }
            }
            string sign = Security.EncryptMD5(sb.ToString().TrimEnd('&'));
            return sign;
        }
        public static string CreateMd5Sign(Hashtable parameters)
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(parameters.Keys);
            akeys.Sort();//sort
            foreach (string k in akeys)
            {
                string v = (string)parameters[k];
                sb.Append(k + "=" + v + "&");
            }
            string sign = Security.EncryptMD5(sb.ToString().TrimEnd('&'));
            return sign;
        }
    }
}